'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/user/kh/wx_ads 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		const db = uniCloud.database();
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, _ } = util;
		let { uid, reward_num, wxad_id, maxlimit, todayStart } = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------
		let today_count = await db.collection('a_wxads').where({
			time: _.gt(todayStart),
			user_id: userInfo._id,
			type: "wxads"
		}).count()

		//如果今日已达标
		if (today_count.total > maxlimit * 1 - 1) {
			res.tips = "今日已达标，请明天再来";
			return res;
		}

		//给用户增加金豆余额
		res.update = await db.collection('uni-id-users').doc(userInfo._id).update({
			balance: _.inc(reward_num)
		})

		res.add = await db.collection('a_wxads').add({
			user_id: userInfo._id,
			user_nickname: userInfo.nickname || "",
			reward_num: reward_num, //奖励金豆数
			wxad_id: wxad_id,
			type: "wxads",
			appid: userInfo.appid,
			appname: userInfo.appname,
			os_name: originalParam.context.osName || "", //用户充值时的系统
			_add_time: new Date().getTime(),
			_add_time_str: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
		})

		//添加金豆收支明细
		res.add_jindou = await db.collection('a_jindou_detail').add({
			user_id: userInfo._id,
			nickname: userInfo.nickname || '匿名用户',
			change_num: reward_num, //扣除的金豆数量
			change_reason: "看广告奖励" + reward_num + "金豆",
			type: "income", //类型：expend:支出,income:收入。
			tfid: userInfo.tfid || "0", //投放链接的系统_ID
			invite_code: userInfo.invite_code || "0",
			ad_id: userInfo.ad_id || "0",
			os_name: originalParam.context.osName || "未知", //用户当时的系统
			appid: userInfo.appid || "0",
			appname: userInfo.appname || "0",
			_add_time: new Date().getTime()
		})


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
